package com.itholmes.xmlToJava;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DOM4J {
	public static void main(String[] args) {
		// 创建SAXReader的对象reader
		SAXReader reader = new SAXReader();
		try {
			//通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
			Document document = reader.read(new File("src/resources/books.xml"));
			//通过document对象获取根节点rootElement
			Element rootElement = document.getRootElement();
			//通过rootElement对象的elementIterator方法获取迭代器
			Iterator<Element> elementIterator = rootElement.elementIterator();
			//遍历迭代器，获取根节点的内容
			while(elementIterator.hasNext()) {
				System.out.println("=====开始遍历某一本书=====");
				Element book = elementIterator.next();
				// 获取book的属性名以及 属性值
				List<Attribute> book_attrs_list = book.attributes();
				for (Attribute attr : book_attrs_list) {
                    System.out.println("属性名：" + attr.getName() + "--属性值："
                            + attr.getValue());
                }
				
				Iterator itt = book.elementIterator();
                while (itt.hasNext()) {
                    Element bookChild = (Element) itt.next();
                    System.out.println("节点名：" + bookChild.getName() + "--节点值：" + bookChild.getStringValue());
                }
                System.out.println("=====结束遍历某一本书=====");
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
